package com.duowan.realtime.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class SqlFunctions {

	private static final char DEFAULT_LEVEL_SEPARATOR_CHAR = '/';
	private static String UTF8 = "UTF-8";
	
	/**
	 * 	assertEquals("www.mysql",udf.evaluate("www.mysql.com", ".", 2));
	 * 	assertEquals("mysql.com",udf.evaluate("www.mysql.com", ".", -2));
	 * @param input
	 * @param stripChars
	 * @param index
	 * @return
	 */
	public static String subStringIndex(String input, String stripChars, int index){
		String[] al = StringUtils.split(input, stripChars);
		if (al == null || stripChars == null || index == 0) {
			return null;
		}
		int indexAbs = Math.abs(index)>=al.length ? al.length: Math.abs(index);
		String[] result = new String[indexAbs];
		List<String> tmp = Arrays.asList(al);
		if (index > 0) {
			System.arraycopy(tmp.toArray(), 0, result, 0, indexAbs);
			return StringUtils.join(result, stripChars);
		}
		// 反向取值
		Collections.reverse(tmp);
		System.arraycopy(tmp.toArray(), 0, result, 0, indexAbs);
		List<String> res = Arrays.asList(result);
		Collections.reverse(res);
		return StringUtils.join(res, stripChars);
	}
	
	public static String getLevels(String input ,int level) {
		String[] al = StringUtils.split(input,DEFAULT_LEVEL_SEPARATOR_CHAR);
		if(al == null || al.length < level ) {
			return null;
		}
		if(level<=0){
			return "" +  al.length;
		}
		String[] result = new String[level];
		System.arraycopy(al, 0, result, 0, level);
		return StringUtils.join(result,'/');
	}
	
	public static String decode(String str) {
		try {
			return URLDecoder.decode(str, UTF8);
		} catch (Exception e) {
			//
		}
		return str ; 
	}
	
	public static String concat(String[] inputs){
		StringBuffer sb = new StringBuffer();
		for (String input : inputs) {
			sb.append(input);
		}
		return sb.toString();
	}
	
}
